import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect, routerRedux } from 'dva';
import Icon, { DownOutlined, ExclamationCircleOutlined, UpOutlined } from '@ant-design/icons';
import { message } from 'antd';
import { ModalC, TableC } from '../../../comps';
import styles from './index.less';
import tipsIcon from '../../../assets/busi/userView/tips_icon.png';
import eventIcon from '../../../assets/busi/userView/event_icon.png';
import investmentIcon from '../../../assets/busi/userView/investment_icon.png';
import marketIcon from '../../../assets/busi/userView/market_icon.png';
import eventBg from '../../../assets/busi/userView/event_bg.png';
import investmentBg from '../../../assets/busi/userView/investment_bg.png';
import marketBg from '../../../assets/busi/userView/market_bg.png';

@connect(({ loading, investmentTipsM }) => ({
  loading,
  investmentTipsM,
}))
export default class InvestmentTips extends PureComponent {
  state = {
    showInfo: false, // 是否显示信息详情
    pricieResults: false, // 是否有未复核的定价结果
    undelivered: false, // 是否有未交收管理
    check: false, // 是否有与估值核对不一致的资金与持仓
    stressReport: false, // 是否有压力测试报告
    cashReport: false, // 是否有现金管理报告信息
    productId: '', // 现金管理报告关联产品
    visible: false,
    num1: 0, // 预警条目
    num2: 0, // 禁止条目
    columns: [], // 当前展示表格数据
    dataSource: [],
    columns1: [], // 负面舆情数据
    dataSource1: [],
    columns2: [], // 评级下调
    dataSource2: [],
    columns3: [], // 成交偏离度
    dataSource3: [],
    columns4: [], // 行为事件
    dataSource4: [],
    columns5: [], // 登记事件
    dataSource5: [],
    modalTitle: '', // 弹出框标题
    tableType: undefined, // 当前打开table
  };
  UNSAFE_componentWillMount() {
    this.getUnreadInfo();
    this.getTableData();
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}

  // 打开消息通知index.less
  openInfo = (tipsNum) => {
    if (!tipsNum) {
      message.warning('暂无未读消息');
      return;
    }
    this.setState({
      showInfo: !this.state.showInfo,
    });
  };

  // 获取未读通知
  getUnreadInfo = () => {
    const { dispatch } = this.props;
    // 获取定价复核、估值核对、压力测试报告、现金管理报告未读消息
    dispatch({
      type: 'investmentTipsM/getUnreadList',
      payload: {},
      callback: (data) => {
        if (data) {
          let time = moment(data.stressReportTime).format('YYYY') + '年';
          let month = moment(data.stressReportTime).format('MM');
          if (data.stressReport && data.stressReportTime) {
            if (month >= '01' && month <= '03') {
              time = time + '一季度';
            }
            // 第二季度
            if (month >= '04' && month <= '06') {
              time = time + '二季度';
            }
            // 第三季度
            if (month >= '07' && month <= '09') {
              time = time + '三季度';
            }
            // 第四季度
            if (month >= '10' && month <= '12') {
              time = time + '四季度';
            }
          }
          this.setState({
            pricieResults: data.pricieResults == '1' ? true : false,
            check: data.check == '1' ? true : false,
            stressReport: data.stressReport == '1' ? true : false,
            cashReport: data.cashReport == '1' ? true : false,
            stressReportTime: time,
            cashReportTime: data.cashReportTime,
            productId: data.productId,
            productCode: data.productCode,
          });
        }
      },
    });
    // 未交收管理--交易交收
    dispatch({
      type: 'investmentTipsM/getUndeliveredList',
      payload: {
        params: {
          search_GTE_createdTs: moment().format('YYYY-MM-DD'),
          search_IN_method: '0;1',
          search_LTE_createdTs: moment().format('YYYY-MM-DD'),
          userId: localStorage.getItem('antd-pro-userId'),
        },
        current: 1,
        pageSize: 999,
      },
      callback: (data) => {
        let arr = data && data.length ? data.filter((item) => item.instructionStatus == '6') : [];
        if (arr && arr.length) {
          this.setState({
            undelivered: arr && arr.length ? true : false,
          });
        } else {
          // 未交收管理--行为交收
          dispatch({
            type: 'investmentTipsM/getUndeliveredList2',
            payload: {
              params: {
                search_GTE_createdTs: moment().format('YYYY-MM-DD'),
                search_IN_method: '0;1',
                search_LTE_createdTs: moment().format('YYYY-MM-DD'),
                userId: localStorage.getItem('antd-pro-userId'),
              },
              current: 1,
              pageSize: 20,
            },
            callback: (data2) => {
              if (data2 && data2.length) {
                let arr2 = data2.filter((item) => item.instructionStatus == '6');
                this.setState({
                  undelivered: arr2 && arr2.length ? true : false,
                });
              }
            },
          });
        }
      },
    });
  };

  // 获取表格数据
  getTableData = () => {
    const { dispatch } = this.props;
    // 负面舆情
    dispatch({
      type: 'investmentTipsM/getNegativeData',
      payload: {},
      callback: (columns, data) => {
        this.setState({
          columns1: columns,
          dataSource1: data || [],
        });
      },
    });
    // 评级下调
    dispatch({
      type: 'investmentTipsM/getRatingData',
      payload: {},
      callback: (columns, data) => {
        this.setState({
          columns2: columns,
          dataSource2: data || [],
        });
      },
    });
    // 成交偏离度
    dispatch({
      type: 'investmentTipsM/getTransDeviationData',
      payload: {},
      callback: (columns, data) => {
        this.setState({
          columns3: columns,
          dataSource3: data || [],
        });
      },
    });
    // 投资限制
    dispatch({
      type: 'investmentTipsM/getRulesResultDta',
      payload: {
        currentPage: 1,
        numInPage: 999,
        type: 'first',
      },
      callback: (num1, num2) => {
        this.setState({
          num1: num1,
          num2: num2,
        });
      },
    });
    // 行为事件
    dispatch({
      type: 'investmentTipsM/getBehaviorData',
      payload: {},
      callback: (columns, data) => {
        this.setState({
          columns4: columns,
          dataSource4: data || [],
        });
      },
    });
    // 登记事件
    dispatch({
      type: 'investmentTipsM/getRegisterData',
      payload: {},
      callback: (columns, data) => {
        this.setState({
          columns5: columns,
          dataSource5: data || [],
        });
      },
    });
  };

  // 打开表格弹窗
  openModal = (columns, dataSource, title, type) => {
    this.setState({
      visible: true,
      columns: columns,
      dataSource: dataSource,
      modalTitle: title,
      tableType: type,
    });
  };

  cancel = () => {
    this.setState({
      visible: false,
    });
  };

  tableModal = () => {
    const { columns, dataSource } = this.state;
    let newColumns = this.changeColumns(columns);
    return <TableC columns={newColumns} dataSource={dataSource} hidePage={true} scroll={{ y: 260 }} rowKey='id' />;
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    const { tableType } = this.state;
    let data = columns;
    if (data && data.length) {
      data.map((item) => {
        if (item.key == 'productName') {
          // 行为事件:跳转至【组合管理】-【组合日历】
          if (tableType == '14') {
            item.render = (text, record) => {
              let productCode = record.productCode ? record.productCode.split(',')[0] : '';
              return <a onClick={() => this.tableJumpTable(tableType, record)}>{productCode + '-' + text}</a>;
            };
          }
          // 登记事件:跳转至【组合管理】-【组合日历】
          if (tableType == '15') {
            item.render = (text, record) => {
              let productCode = record.productCode ? record.productCode.split(',')[0] : '';
              return <a onClick={() => this.tableJumpTable(tableType, record)}>{productCode + '-' + text}</a>;
            };
          }
        }
        if (item.key == 'securityName') {
          // 评级下调：【市场分析】-【债券评级监控】
          if (tableType == '12') {
            item.render = (text, record) => {
              return <a onClick={() => this.tableJumpTable(tableType, record)}>{record.securityCode + '-' + record.securityName}</a>;
            };
          }
          // 成交偏离度：【市场分析】-【债券偏离度分析】
          if (tableType == '13') {
            item.render = (text, record) => {
              return <a onClick={() => this.tableJumpTable(tableType, record)}>{record.tradingCode + '-' + record.securityName}</a>;
            };
          }
          // 行为事件:跳转至【组合管理】-【组合日历】
          if (tableType == '14' || tableType == '15') {
            item.render = (text, record) => {
              return record.securityCode + '-' + text;
            };
          }
        }
        if (item.key == 'newsTitle') {
          // 负面舆情：跳转至【市场分析】-【主体舆情监控】-【新闻标题】
          item.render = (text, record) => {
            return <a onClick={() => this.tableJumpTable(tableType, record)}>{text}</a>;
          };
        }
      });
    }
    return data;
  };

  // 未读消息跳转页面
  jumpPage = (type) => {
    let url;
    let obj = {};
    // 资产定价/非标估值复核
    if (type == '1') {
      url = '/assetPricing/nonstandardValueReview';
      obj = {
        activeKey: '3',
        type: type,
      };
      sessionStorage.setItem('jumpInfo', JSON.stringify(obj));
    }
    // 运营管理/交收管理
    if (type == '2') {
      url = '/OperationManagement/bookkeepingSettlement';
      obj = {
        type: type,
      };
      sessionStorage.setItem('jumpInfo', JSON.stringify(obj));
    }
    // 库存管理/估值核对
    if (type == '3') {
      url = '/inventoryMnt/positionCompare';
    }
    // 压力测试/压力测试报告
    if (type == '4') {
      url = '/stressTest/pressureReport';
    }
    // 报告服务/现金管理理财新规报告
    if (type == '5') {
      url = '/reportingServices/cashManagementReport';
      obj = {
        cashReportTime: this.state.cashReportTime,
        productId: this.state.productId,
        productCode: this.state.productCode,
        type: type,
      };
      sessionStorage.setItem('jumpInfo', JSON.stringify(obj));
    }
    this.props.dispatch(routerRedux.push(url));
  };

  // 表格跳转页面
  tableJumpTable = (tableType, record) => {
    if (tableType == '11') {
      //负面舆情
      const obj = {
        bondID: record.newId,
        type: 'news',
        comid: record.comcode,
      };
      sessionStorage.setItem('publicSentiment', JSON.stringify(obj));
      this.props.dispatch(routerRedux.push(`/marketAnalysis/Monitorpublicopinion/newsDetail`));
    }
    if (tableType == '12') {
      // 评级下调
      const obj = {
        activeKey: '2',
        securityCode: record.securityCode,
        securityName: record.securityName,
        type: tableType,
      };
      sessionStorage.setItem('jumpInfo', JSON.stringify(obj));
      this.props.dispatch(routerRedux.push(`/marketAnalysis/Ratingmonitoring`));
    }
    if (tableType == '13') {
      // 成交偏离度
      const obj = {
        code: record.exchangeCode + '-' + record.tradingCode,
        securityCode: record.securityCode,
        type: tableType,
      };
      sessionStorage.setItem('jumpInfo', JSON.stringify(obj));
      this.props.dispatch(routerRedux.push(`/marketAnalysis/bondDeviationMonitoring/bondDeviationAnalysis`));
    }
    if (tableType == '14') {
      console.log(record);
      //行为事件
      const obj = {
        portfolioCode: record?.productCode ? record?.productCode.split(',') : [],
        portfolioId: record.productId,
        productName: record.productName,
        type: tableType,
      };
      sessionStorage.setItem('jumpInfo', JSON.stringify(obj));
      this.props.dispatch(routerRedux.push(`/portfolioBuild/investmentCalendar`));
    }
    if (tableType == '15') {
      //登记事件
      const obj = {
        portfolioCode: record?.productCode ? record?.productCode.split(',') : [],
        portfolioId: record.productId,
        productName: record.productName,
        type: tableType,
      };
      sessionStorage.setItem('jumpInfo', JSON.stringify(obj));
      this.props.dispatch(routerRedux.push(`/portfolioBuild/investmentCalendar`));
    }
    if (tableType == '16' || tableType == '17') {
      //负面舆情
      const obj = {
        type: tableType,
      };
      sessionStorage.setItem('jumpInfo', JSON.stringify(obj));
      this.props.dispatch(routerRedux.push(`/riskMonitor/limitMonitoring`));
    }
    this.setState({
      visible: false,
    });
  };
  render() {
    const {
      showInfo,
      pricieResults,
      undelivered,
      check,
      stressReport,
      stressReportTime,
      cashReport,
      cashReportTime,
      visible,
      columns1,
      dataSource1,
      columns2,
      dataSource2,
      columns3,
      dataSource3,
      columns4,
      dataSource4,
      columns5,
      dataSource5,
      num1,
      num2,
      modalTitle,
    } = this.state;
    let arr = [pricieResults, undelivered, check, stressReport, cashReport];
    let tipsNum = 0;
    arr.map((item) => {
      if (item) tipsNum++;
    });
    return (
      <div className={styles.investmentTips}>
        <div className={styles.title}>
          <Icon component={() => <img src={tipsIcon} alt='icon' style={{ marginRight: '10px', width: '22px' }} />} />
          投资提示
        </div>
        <div className={styles.tipsInfo}>
          {tipsNum ? (
            <a className={styles.tips} onClick={() => this.openInfo(tipsNum)}>
              <div>
                <ExclamationCircleOutlined style={{ marginRight: '6px' }} />
                您有 {tipsNum} 条未读通知，请查看。
              </div>
              <DownOutlined />
            </a>
          ) : (
            ''
          )}
          <div className={styles.info} style={{ height: showInfo ? `${tipsNum * 40 + 32}px` : 0 }}>
            <a className={styles.top} onClick={() => this.openInfo(tipsNum)}>
              <div>点击查看详情</div>
              <UpOutlined style={{ color: '#4376FF' }} />
            </a>
            {pricieResults ? (
              <a className={styles.list} onClick={() => this.jumpPage('1')}>
                <ExclamationCircleOutlined style={{ color: '#4376FF', marginRight: '6px' }} />
                您有未复核的定价结果，请点击查看。
              </a>
            ) : (
              ''
            )}
            {undelivered ? (
              <a className={styles.list} onClick={() => this.jumpPage('2')}>
                <ExclamationCircleOutlined style={{ color: '#4376FF', marginRight: '6px' }} />
                您有待交收的交易，请点击查看。
              </a>
            ) : (
              ''
            )}
            {check ? (
              <a className={styles.list} onClick={() => this.jumpPage('3')}>
                <ExclamationCircleOutlined style={{ color: '#4376FF', marginRight: '6px' }} />
                您有与估值核对不一致的资金与持仓，请点击查看。
              </a>
            ) : (
              ''
            )}
            {stressReport ? (
              <a className={styles.list} onClick={() => this.jumpPage('4')}>
                <ExclamationCircleOutlined style={{ color: '#4376FF', marginRight: '6px' }} />
                {stressReportTime}压力测试报告已出具，请点击查看。
              </a>
            ) : (
              ''
            )}
            {cashReport ? (
              <a className={styles.list} onClick={() => this.jumpPage('5')}>
                <ExclamationCircleOutlined style={{ color: '#4376FF', marginRight: '6px' }} />
                {cashReportTime}现金管理报告已出具，请点击查看。
              </a>
            ) : (
              ''
            )}
          </div>
        </div>
        <div className={styles.content}>
          <div className={styles.contentList}>
            <div className={styles.title}>
              <Icon component={() => <img src={marketIcon} alt='icon' style={{ marginRight: '10px', width: '24px' }} />} />
              市场信息
            </div>
            <div className={styles.list}>
              <span>负面舆情</span>
              <span>
                <a
                  className={styles.num}
                  onClick={() => {
                    this.openModal(columns1, dataSource1, '负面舆情', '11');
                  }}
                >
                  {dataSource1.length}
                </a>{' '}
                条
              </span>
            </div>
            <div className={styles.list}>
              <span>评级下调</span>
              <span>
                <a
                  className={styles.num}
                  onClick={() => {
                    this.openModal(columns2, dataSource2, '评级下调', '12');
                  }}
                >
                  {dataSource2.length}
                </a>{' '}
                条
              </span>
            </div>
            <div className={styles.list}>
              <span>成交偏离度</span>
              <span>
                <a
                  className={styles.num}
                  onClick={() => {
                    this.openModal(columns3, dataSource3, '成交偏离度', '13');
                  }}
                >
                  {dataSource3.length}
                </a>{' '}
                条
              </span>
            </div>
            <div className={styles.bg}>
              <img src={marketBg} />
            </div>
          </div>
          <div className={styles.contentList}>
            <div className={styles.title}>
              <Icon component={() => <img src={investmentIcon} alt='icon' style={{ marginRight: '10px', width: '24px' }} />} />
              投资限制
            </div>
            <div className={styles.list}>
              <span>预警条目</span>
              <span>
                <a
                  className={styles.num}
                  onClick={() => {
                    this.tableJumpTable('16');
                  }}
                >
                  {num1}
                </a>{' '}
                条
              </span>
            </div>
            <div className={styles.list}>
              <span>禁止条目</span>
              <span>
                <a
                  className={styles.num}
                  onClick={() => {
                    this.tableJumpTable('17');
                  }}
                >
                  {num2}
                </a>{' '}
                条
              </span>
            </div>
            <div className={styles.bg}>
              <img src={investmentBg} />
            </div>
          </div>
          <div className={styles.contentList}>
            <div className={styles.title}>
              <Icon component={() => <img src={eventIcon} alt='icon' style={{ marginRight: '10px', width: '24px' }} />} />
              标的事件
            </div>
            <div className={styles.list}>
              <span>行为事件</span>
              <span>
                <a
                  className={styles.num}
                  onClick={() => {
                    this.openModal(columns4, dataSource4, '行为事件', '14');
                  }}
                >
                  {dataSource4.length}
                </a>{' '}
                条
              </span>
            </div>
            <div className={styles.list}>
              <span>登记事件</span>
              <span>
                <a
                  className={styles.num}
                  onClick={() => {
                    this.openModal(columns5, dataSource5, '登记事件', '15');
                  }}
                >
                  {dataSource5.length}
                </a>{' '}
                条
              </span>
            </div>
            <div className={styles.bg}>
              <img src={eventBg} />
            </div>
          </div>
        </div>
        <ModalC title={modalTitle} visible={visible} footer={null} onCancel={this.cancel} width={720}>
          <div>{this.tableModal()}</div>
        </ModalC>
      </div>
    );
  }
}
